package cn.cellcom.agent.struts.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.cellcom.agent.common.AgentEnv;
import cn.cellcom.agent.hql.TCrmHql;
import cn.cellcom.agent.pojo.TCrm;
import cn.cellcom.agent.struts.form.TCrmForm;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.file.FileLoad;
import cn.cellcom.jar.file.FileProcessor;
import cn.cellcom.jar.file.IFileLoad;
import cn.cellcom.jar.file.IFileProcessor;
import cn.cellcom.jar.pagination.AbstractPaginationBiz;
import cn.cellcom.jar.pagination.IPaginationBiz;
import cn.cellcom.jar.port.ExportTemplate;
import cn.cellcom.jar.port.IDataPort;
import cn.cellcom.jar.port.JxlPort;
import cn.cellcom.jar.util.BeanUtil;
import cn.cellcom.jar.util.CU;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;

public class TCrmDpAct extends DispatchAction {

	private IPaginationBiz pbiz;

	private AbstractBiz cbiz;

	private Log log = LogFactory.getLog(this.getClass());

	/**
	 * 查询记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		form = (ActionForm) AbstractPaginationBiz.getPaginationActionForm(req, form);
		List list = null;
		try {
			log.info("查询的语句：TCrmHql()");
			list = pbiz.pagination(mapping, form, req, new TCrmHql()).getDataResult();

			req.setAttribute(Env.DATA_NAME, list);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作出现错误", e, mapping, req);
		}
		if("select2".equals(req.getParameter("from"))) {
			List<Map<String, String>> mlist = new ArrayList<Map<String, String>>();
			for (int i = 0; i < list.size(); i++) {
				TCrm crm = (TCrm) list.get(i);
				Map<String, String> e = new HashMap<String, String>();
				e.put("id", crm.getId());
				e.put("text", crm.getName() + "[电话:" + CU.valueOf(crm.getPhone()) + "]");
				mlist.add(e);
			}
			Response.succ(rep, mlist);
			return null;
		} else {
			req.setAttribute("levellist", BeanUtil.startWith("TCrm-level"));
			req.setAttribute("sexlist", BeanUtil.startWith("TCrm-sex"));
			req.setAttribute("statuslist", BeanUtil.startWith("TCrm-status"));
			req.setAttribute("typelist", BeanUtil.startWith("TCrm-type"));
		}
		return mapping.findForward("list");
	}

	/**
	 * 准备记录添加
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		// levellist是从context中读取的，这里无需有读取代码
		// statuslist是从context中读取的，这里无需有读取代码
		// sexlist是从context中读取的，这里无需有读取代码
		req.setAttribute("levellist", BeanUtil.startWith("TCrm-level"));
		req.setAttribute("sexlist", BeanUtil.startWith("TCrm-sex"));
		req.setAttribute("statuslist", BeanUtil.startWith("TCrm-status"));
		req.setAttribute("typelist", BeanUtil.startWith("TCrm-type"));

		return mapping.findForward("add");
	}

	/**
	 * 执行记录添加
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TCrmForm fm = (TCrmForm) form;
		Object obj = null;
		try {
			obj = cbiz.add(req, fm, null);
		} catch (MyException e) {
			LogUtil.e(this.clazz, "新增数据出现异常", e);
		}
		log.info("新增记录结果：" + obj);
		String message;
		if (obj == null || !(obj instanceof TCrm)) {
			req.setAttribute(Env.DATA_NAME, "操作失败，" + obj);
			return mapping.findForward("error");
		} else {
			message = "记录添加成功";
		}

		add(mapping, fm, req, rep);
		// req.setAttribute("success", fm);
		req.setAttribute(Env.DATA_NAME, message);
		return mapping.findForward("add");
	}

	/**
	 * 准备修改记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward modify(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TCrmForm fm = (TCrmForm) form;
		try {
			java.lang.String key = fm.getId();
			TCrm rf = (TCrm) cbiz.getDao().myGet(TCrm.class, key);
			if (rf == null) {
				req.setAttribute(Env.DATA_NAME, "读取数据错误");
				return mapping.findForward("error");
			}
			req.setAttribute(Env.DATA_NAME, rf);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "读取数据错误", e, mapping, req);
		}
		// levellist是从context中读取的，这里无需有读取代码
		// statuslist是从context中读取的，这里无需有读取代码
		// sexlist是从context中读取的，这里无需有读取代码
		// typelist是从context中读取的，这里无需有读取代码
		req.setAttribute("levellist", BeanUtil.startWith("TCrm-level"));
		req.setAttribute("sexlist", BeanUtil.startWith("TCrm-sex"));
		req.setAttribute("statuslist", BeanUtil.startWith("TCrm-status"));
		req.setAttribute("typelist", BeanUtil.startWith("TCrm-type"));
		return mapping.findForward("modify");
	}

	/**
	 * 执行记录修改
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doModify(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TCrmForm fm = (TCrmForm) form;
		Object obj = null;
		try {
			obj = cbiz.modify(req, fm, null);
		} catch (MyException e) {
			LogUtil.e(this.clazz, "修改数据出现异常", e);
		}
		log.info("修改记录结果：" + obj);
		if (obj == null || !(obj instanceof TCrm)) {
			req.setAttribute(Env.DATA_NAME, "操作失败，" + obj);
			return mapping.findForward("error");
		}
		req.setAttribute(Env.DATA_NAME, "记录修改成功");
		return mapping.findForward("success");
	}

	/**
	 * 导出数据
	 * 
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doExport(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {

		try {
			TCrmHql hql0 = new TCrmHql();
			List list = this.cbiz.getDao().myList(hql0.getHql(req, form), hql0.getParaValue(req, form));
			if (list == null || list.size() < 1) {
				req.setAttribute(Env.DATA_NAME, "本次查询没有数据，所以不做导出");
				return mapping.findForward("success");
			}

			ExportTemplate template = new ExportTemplate() {
				private static final long serialVersionUID = 1L;

				@Override
				public void setRow(DataRow row, Object obj) {
					TCrm pojo = (TCrm) obj;
					row.add(CU.valueOf(pojo.getId()));
					row.add(CU.valueOf(pojo.getOrg()));
					row.add(CU.valueOf(pojo.getName()));
					row.add(CU.valueOf(pojo.getPhone()));
					row.add(CU.valueOf(pojo.getEmail()));
					row.add(CU.valueOf(pojo.getLevel()));
					row.add(CU.valueOf(pojo.getStatus()));
					row.add(CU.valueOf(pojo.getQq()));
					row.add(CU.valueOf(pojo.getSex()));
					row.add(CU.valueOf(pojo.getCompany()));
					row.add(CU.valueOf(pojo.getProvince()));
					row.add(CU.valueOf(pojo.getCity()));
					row.add(CU.valueOf(pojo.getMemo()));
					row.add(CU.valueOf(pojo.getTid()));
					row.add(CU.valueOf(pojo.getType()));
					row.add(CU.valueOf(pojo.getExtend1()));
					row.add(CU.valueOf(pojo.getExtend2()));
					row.add(CU.valueOf(pojo.getExtend3()));
					row.add(CU.valueOf(pojo.getExtend4()));
					row.add(CU.valueOf(pojo.getExtend5()));
					row.add(CU.valueOf(pojo.getExtend6()));
					row.add(CU.valueOf(pojo.getExtend7()));
					row.add(CU.valueOf(pojo.getExtend8()));
					row.add(CU.valueOf(pojo.getExtend9()));
					row.add(CU.valueOf(pojo.getExtend10()));

				}
			};
			String root3path3file = AgentEnv.EXPORT_PATH + CU.getSerial(".xls");
			template.setRoot3path3file(root3path3file);
			template.setContentTitle(new String[] { " id", " 企业", " 内部员工", " 姓名", " 电话", " 邮箱", " 等级", " 状态", " QQ", " 性别", " 企业", " 省份", " 城市",
					" 备注", " CID", " 类型", " extend1", " extend2", " extend3", " extend4", " extend5", " extend6", " extend7", " extend8", " extend9",
					" extend10" });

			IDataPort port = new JxlPort();
			template.setDataList(list);
			port.export(template);

			IFileLoad fl = new FileLoad();
			fl.download(req, rep, this.servlet.getServletConfig(), root3path3file);

			IFileProcessor fp = new FileProcessor();
			fp.delete(root3path3file);

		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作出现错误", e, mapping, req);
		}

		return null;
	}

	public void setCbiz(AbstractBiz cbiz) {
		this.cbiz = cbiz;
	}

	public void setPbiz(IPaginationBiz pbiz) {
		this.pbiz = pbiz;
	}
}
